package com.example.demotest.demotest.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * @author x_weidanlang
 * @version 1.0
 * @date 2022/2/9 10:03
 */
@Slf4j
@ControllerAdvice()
public class ErrorControllerHandler implements ErrorController {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String,Object>> handleValidationExceptions(MethodArgumentNotValidException ex){
        System.out.println("MethodArgumentNotValidException异常处理"+ex.getMessage());
        List<String> errorsList=new ArrayList<>();
        Map<String,Object> errors=new Hashtable<>();
        ex.getBindingResult().getAllErrors().forEach((error)->{
            String fieldName=((FieldError)error).getField();
            String errorMessage=error.getDefaultMessage();
            errorsList.add("参数"+fieldName +errorMessage);
//            errors.put(fieldName,errorMessage);
        });
        errors.put("msg","参数不能为空");
        errors.put("code",400);
        errors.put("success",false);
        errors.put("data",errorsList);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
    }

    //	约束冲突异常异常处理
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Map<String,Object>>  handleConstraintViolationException(ConstraintViolationException ex){
        System.out.println("ConstraintViolationException异常处理"+ex.getMessage());
        Map<String,Object> errors=new Hashtable<>();
        errors.put("msg",ex.getMessage());
        errors.put("code",400);
        errors.put("success",false);
        errors.put("data","");
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
//        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }
//    @ResponseBody
//    @ExceptionHandler(HttpMessageNotReadableException.class)
//    public ResponseEntity<Map<String,Object>> globalException(HttpServletResponse response, HttpMessageNotReadableException ex){
//        log.error("HttpMessageNotReadableException,错误信息：{}",ex.getMessage());
//        Map<String,Object> errors=new Hashtable<>();
//        errors.put("msg","请求错误，请检查数据格式是否正确！");
//        errors.put("code",400);
//        errors.put("success",false);
//        errors.put("data","");
//        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
//    }

}
